class HomeApp {
    constructor() {
        this.currentStage = null;
        this.currentCourse = null;
        this.currentContent = null; // 添加当前内容属性

        // 检查用户是否已登录
        this.checkAuthentication();

        // 初始化各个面板
        this.userPanel = new UserPanel(this);
        this.courseStagePanel = new CourseStagePanel(this);
        this.courseSectionPanel = new CourseSectionPanel(this);
        this.courseContentPanel = new CourseContentPanel(this);
        this.authorizationPanel = new AuthorizationPanel(this);
        this.audioPanel = new AudioPanel(this); // 添加音频面板
        this.feedbackPanel = new FeedbackPanel(this); // 添加意见反馈面板
        this.appVersionPanel = new AppVersionPanel(this); // 添加APP版本管理面板

        // 初始化应用
        this.init();
    }

    // 检查用户认证状态
    checkAuthentication() {
        const token = localStorage.getItem('Authorization');
        if (!token) {
            // 没有token，重定向到登录页面
            window.location.href = '/login';
            return;
        }
        // 设置全局请求头
        this.setGlobalHeaders(token);
    }

    // 设置全局请求头
    setGlobalHeaders(token) {
        // 保存token到实例变量
        this.authToken = token;

        // 可以在这里设置全局的fetch默认选项
        this.defaultHeaders = {
            'Authorization': `Bearer ${token}`,
            'Content-Type': 'application/json'
        };
    }

    // 带认证的fetch请求封装
    async authenticatedFetch(url, options = {}) {
        // 不要为 FormData 请求设置 Content-Type，让浏览器自动设置
        const headers = {
            'Authorization': this.defaultHeaders.Authorization,
            ...options.headers
        };

        const response = await fetch(url, {
            ...options,
            headers: headers
        });

        // 如果token过期，重定向到登录页
        if (response.status === 401) {
            localStorage.removeItem('Authorization');
            window.location.href = '/login';
            return null;
        }

        return response;
    }

    init() {
        // 初始化导航
        this.initNavigation();

        // 初始化各个面板
        this.userPanel.initUserPanel();
        this.initCoursePanels(); // 初始化课程相关面板
        this.authorizationPanel.initAuthorizationPanel();
        this.audioPanel.initAudioManagement(); // 初始化音频面板
        this.feedbackPanel.initFeedbackPanel(); // 初始化意见反馈面板
        this.appVersionPanel.initAppVersionPanel(); // 初始化APP版本管理面板

        // 初始化退出登录按钮
        this.initLogout();
    }

    initNavigation() {
        // 主导航
        document.querySelectorAll('.nav-item').forEach(item => {
            item.addEventListener('click', (e) => {
                const target = item.getAttribute('data-target');
                this.switchPanel(target);
            });
        });

        // 课程管理子导航
        document.querySelectorAll('.sub-nav-btn').forEach(btn => {
            btn.addEventListener('click', (e) => {
                const target = btn.getAttribute('data-target');
                this.switchSubPanel(target);
            });
        });
    }

    // 初始化课程相关面板
    initCoursePanels() {
        // 初始化课程阶段管理
        this.courseStagePanel.initCourseStageManagement();
        
        // 初始化课程节选管理
        this.courseSectionPanel.initCourseManagement();
        
        // 初始化课程内容管理
        this.courseContentPanel.initCourseContentManagement();
        
        // 如果课程面板处于激活状态，则加载课程阶段数据
        const coursesPanel = document.getElementById('courses-panel');
        if (coursesPanel && coursesPanel.classList.contains('active')) {
            this.courseStagePanel.loadCourseStages();
        }
    }

    switchPanel(target) {
        // 更新主导航状态
        document.querySelectorAll('.nav-item').forEach(item => {
            item.classList.remove('active');
        });
        document.querySelector(`.nav-item[data-target="${target}"]`).classList.add('active');

        // 显示目标面板，隐藏其他面板
        document.querySelectorAll('.content-panel').forEach(panel => {
            panel.classList.remove('active');
        });
        document.getElementById(`${target}-panel`).classList.add('active');

        // 根据面板加载数据
        switch (target) {
            case 'users':
                this.userPanel.loadUsers();
                break;
            case 'courses':
                this.courseStagePanel.loadCourseStages();
                break;
            case 'authorizations':
                this.authorizationPanel.loadAuthorizations();
                break;
            case 'app-version':
                this.appVersionPanel.loadCurrentAppVersion();
                break;
            case 'feedback':
                this.feedbackPanel.loadFeedbackList();
                break;
        }
    }

    switchSubPanel(target) {
        // 更新子导航状态
        document.querySelectorAll('.sub-nav-btn').forEach(btn => {
            btn.classList.remove('active');
        });
        document.querySelector(`.sub-nav-btn[data-target="${target}"]`).classList.add('active');

        // 显示目标子面板，隐藏其他子面板
        document.querySelectorAll('.sub-panel').forEach(panel => {
            panel.classList.remove('active');
        });

        switch (target) {
            case 'course-stage':
                document.getElementById('course-stage-panel').classList.add('active');
                this.courseStagePanel.loadCourseStages();
                break;
            case 'course':
                document.getElementById('course-panel').classList.add('active');
                if (this.currentStage) {
                    this.courseSectionPanel.loadCoursesForStage(this.currentStage.id);
                }
                break;
            case 'course-content':
                document.getElementById('course-content-panel').classList.add('active');
                if (this.currentCourse) {
                    this.courseContentPanel.loadCourseContents(this.currentCourse.id);
                }
                break;
            case 'course-audio':
                document.getElementById('course-audio-panel').classList.add('active');
                if (this.currentContent) {
                    this.audioPanel.loadCourseAudios(this.currentContent.id);
                }
                break;
        }

        // 关闭内容详情区域（如果存在）
        this.hideContentDetail();
    }

    initLogout() {
        const logoutBtn = document.getElementById('logout-btn');
        if (logoutBtn) {
            logoutBtn.addEventListener('click', () => {
                // 清除本地存储的token
                localStorage.removeItem('Authorization');
                // 跳转到登录页面
                window.location.href = '/login';
            });
        }
    }

    hideContentDetail() {
        const detailContainer = document.getElementById('content-detail');
        if (detailContainer) {
            detailContainer.style.display = 'none';
        }
    }
}

// 页面加载完成后初始化应用
document.addEventListener('DOMContentLoaded', () => {
    window.homeApp = new HomeApp();
});